//
//  // BDLoginViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDLoginViewController.h"
#import "BDTabBarViewController.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import "BDUserModel.h"
#import "BDDetailLoginViewController.h"
#import "BDLoginPasswordViewController.h"
#import "UMSocialCore/UMSocialCore.h"
#import "BDTishiViewController.h"
#import "CameraPhotoBehavior.h"

@interface  BDLoginViewController ()
{
    NSMutableArray *imageNameArr;
    BOOL clickGetButton;
    UIColor *finishColor;
    BOOL waitCityList;
}
@property (nonatomic, strong) UITextField *userField;
@property (nonatomic, strong) UITextField *passField;

@property (nonatomic, strong) YYLabel *xieyiLabel;
@property (nonatomic, strong) UIButton *agreeButton;

@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *getButton;

@property (nonatomic, strong) UIButton *changeLoginButton;

@end

@implementation  BDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"登录");
    self.userField.keyboardType = UIKeyboardTypeNumberPad;
    self.passField.keyboardType = UIKeyboardTypeNumberPad;
    [self addThirdLoaginView];
    [self bindModel];
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 5, 25 ,25)];
    [backButton setImage:[UIImage imageNamed:@"cha"] forState:UIControlStateNormal];
    
    UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backBarButton;
    
    [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setNavigation{
    [super setNavigation];
}

- (void)addThirdLoaginView{
    UILabel *otherLabel = [[UILabel alloc] init];
    otherLabel.textColor = [UIColor colorWithRed:118/255.0 green:118/255.0 blue:118/255.0 alpha:1.0f];
    otherLabel.font = [UIFont systemFontOfSize:14];
    otherLabel.textAlignment = NSTextAlignmentCenter;
    otherLabel.text = ASLocalizedString(@"其他登录");
    otherLabel.size = CGSizeMake([otherLabel.text widthWithFont:otherLabel.font], 12);
    otherLabel.bottom = self.view.bottom - 146;
    otherLabel.centerX = self.view.width / 2.0;
    [self.view addSubview:otherLabel];
    
    CGFloat lineWidth = (self.view.width - otherLabel.width - (20+10) * 2) / 2.0;
    for (int i = 0; i < 2; i++) {
        UIView *lineView = [[UIView alloc]init];
        lineView.backgroundColor = [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1.0f];
        lineView.size = CGSizeMake(lineWidth, 1);
        lineView.centerY = otherLabel.centerY;
        if (i == 0) {
            lineView.left = 20;
        }else{
            lineView.right = self.view.width - 20;
        }
        [self.view addSubview:lineView];
    }
    
//    imageNameArr = @[@"weixin",@"qq",@"sina"].mutableCopy;
//    if (![QQApiInterface isQQInstalled]) {
//        [imageNameArr removeObject:@"qq"];
//    }
//    if (![WXApi isWXAppInstalled]) {
//        [imageNameArr removeObject:@"weixin"];
//    }

    imageNameArr = @[@"weixin"].mutableCopy;
    
    CGFloat thirdButtonWidth = 45;
    CGFloat thirdSpace = (self.view.width - thirdButtonWidth * imageNameArr.count) / (imageNameArr.count + 1);
    
    for (int i = 0; i < imageNameArr.count; i++) {
        UIButton *thirdButton = [UIButton buttonWithType:UIButtonTypeCustom];
        thirdButton.frame = CGRectMake(thirdSpace + (thirdSpace + thirdButtonWidth) * i, otherLabel.bottom + 20, thirdButtonWidth, thirdButtonWidth);
        [thirdButton setBackgroundImage:[UIImage imageNamed:imageNameArr[i]] forState:UIControlStateNormal];
        thirdButton.tag = 2017 + i;
        [self.view addSubview:thirdButton];
        [thirdButton addTarget:self action:@selector(thirdButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)thirdButtonAction:(UIButton *)button{
    if (self.agreeButton.selected == NO) {
        [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"请阅读并同意《用户服务协议》")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        return;
    }
    NSString *imageName = imageNameArr[button.tag - 2017];
    UMSocialPlatformType platform;
    NSString *agency;
    if ([imageName isEqualToString:@"weixin"]) {
        agency = @"weixin",
        platform= UMSocialPlatformType_WechatSession;
    }else if ([imageName isEqualToString:@"qq"]) {
        agency = @"qq",
        platform= UMSocialPlatformType_QQ;
    }else{
        agency = @"sina",
        platform= UMSocialPlatformType_Sina;
    }
    // BDLog(ASLocalizedString(@"开始点击第三方登录按钮"));
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platform currentViewController:nil completion:^(id result, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                // BDLog(ASLocalizedString(@"错误"));
            }else{
                [MBManager showLoadingAlert:nil clickHidden:NO clickBlock:nil];
                UMSocialUserInfoResponse *resp = result;
                
                [BDUserModel loginUserWithAccount:resp.openid code:resp.accessToken loginType:BDLoginTypeThirdPart completionHandler:^(id obj, NSError *error) {
                    if (error) {
                        if (error.code == 40104 || error.code == BDLoginErrorNotCompletionInfo) {
                            [MBManager hideAlert];
                            BDDetailLoginViewController *detailLoginVC = [[BDDetailLoginViewController alloc] init];
                            detailLoginVC.editType = BDEditTypeThird;
                            detailLoginVC.registType = error.code == 40104 ? BDRegistTypeNoRegist : BDRegistTypeNoNickname;
                            detailLoginVC.nickName = resp.name;
                            detailLoginVC.openid = resp.openid;
                            detailLoginVC.access_token = resp.accessToken;
                            [self.navigationController pushViewController:detailLoginVC animated:YES];
                        }else{
                            //            [MBManager hideAlert];
                            NSString *alert = ASLocalizedString(@"用户名或验证码错误");
                            if (error.code == 40002) {
                                alert = ASLocalizedString(@"验证码错误或失效");
                            }else if (error.code == BDLoginErrorLoginIMFailed) {
                                alert = @"极光IM登录失败";
                            }else if (error.code == BDLoginErrorGetFirendsListFailed) {
                                alert = @"获取好友列表失败";
                            }else if (error.code == BDLoginErrorGetGroupsListFailed) {
                                alert = @"获取好友列表失败";
                            }
                            
                            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
                        }
                    }else{
                        [MBManager hideAlert];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"getConvitasionFromDB" object:nil];
                        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                    }
                }];
            }
        });
    }];
}

//绑定视图模型
- (void)bindModel{
    //绑定发送验证码button是否可以点击和背景颜色
    RACSignal *getEnable = [RACSignal combineLatest:@[self.userField.rac_textSignal] reduce:^id _Nullable{
        return @(self.userField.text.length == 11);
    }];
    RAC(self.getButton, userInteractionEnabled) = getEnable;
    [getEnable subscribeNext:^(id  _Nullable x) {
        if (clickGetButton == NO) {
            self.getButton.backgroundColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
        }else{
            finishColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
        }
    }];
    
    //发送验证码
    [[self.getButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"点击了发送验证的按钮"));
        clickGetButton = YES;
        self.getButton.backgroundColor = kNOValidColor;
        _getButton.userInteractionEnabled = NO;
        
        NSDictionary *para = @{@"mobile":self.userField.text};
        NSString *url = [NSString stringWithFormat:@"%@sms", KBDBaseURL];
        
        RACCommand *getCodeCommand = [BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO];
        RACSignal *getCodeSignal = [getCodeCommand execute:nil];

        [[getCodeSignal deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id  _Nullable x) {
            [self.passField becomeFirstResponder];
            
            @weakify(self);
            __block NSInteger number = 60;
            NSInteger numberLimit = number;
            RACSignal *timeSignal = [[[[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]] take:numberLimit] startWith:[NSDate date]] map:^id(NSDate *date) {
                @strongify(self);
                if (number == 0) {
                    [self.getButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
                    self.getButton.userInteractionEnabled = YES;
                    clickGetButton = NO;
                    self.getButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
                    return @YES;
                }else{
                    [self.getButton setTitle:[NSString stringWithFormat:ASLocalizedString(@"剩余%zd秒"), number] forState:UIControlStateNormal];
//                    // BDLog(ASLocalizedString(@"按钮文本是什么：%@"), [NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number]);
                    number--;
                    return @NO;
                }
            }] takeUntil:self.rac_willDeallocSignal];
            
            _getButton.rac_command = [[RACCommand alloc]initWithEnabled:timeSignal signalBlock:^RACSignal *(id input) {
                number = numberLimit;
                return timeSignal;
            }];
        }];
        //错误处理
        [getCodeSignal subscribeError:^(NSError * _Nullable error) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:ASLocalizedString(@"发送验证码失败，请稍后再试")clickHidden:NO clickBlock:nil];
            [self.getButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
            self.getButton.userInteractionEnabled = YES;
            clickGetButton = NO;
            self.getButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
        }];
    }];
    
    //登录按钮
    [[self.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.view endEditing:YES];
        NSString *alert = nil;
        if (self.userField.text.length != 11) {
            alert = ASLocalizedString(@"请填写合法的手机号");
        }else if (self.passField.text.length == 0) {
            alert = ASLocalizedString(@"请填写验证码");
        }else if (self.passField.text.length != 4) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"验证码填写长度超出范围，是否选择使用密码登录？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"使用密码登录")] clickBlock:^(NSInteger index) {
                if (index == 1) {
                    [self performSelector:@selector(jumpToPasswordLogin) withObject:nil afterDelay:0.2];
                }
            }];
            return;
        }
        if (alert != nil) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
            return;
        }
        if (self.agreeButton.selected == NO) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"请阅读并同意《用户服务协议》")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            return;
        }
        [MBManager showLoadingAlert:nil clickHidden:NO clickBlock:nil];
        
        [BDUserModel loginUserWithAccount:self.userField.text code:self.passField.text loginType:BDLoginTypeVerificationCode completionHandler:^(id obj, NSError *error) {
            if (error) {
                if (error.code == 40104 || error.code == BDLoginErrorNotCompletionInfo) {
                    [MBManager hideAlert];
                    BDDetailLoginViewController *detailLoginVC = [[BDDetailLoginViewController alloc] init];
                    detailLoginVC.editType = BDEditTypePhone;
                    detailLoginVC.registType = error.code == 40104 ? BDRegistTypeNoRegist : BDRegistTypeNoNickname;
                    detailLoginVC.phone = self.userField.text;
                    detailLoginVC.code = self.passField.text;
                    [self.navigationController pushViewController:detailLoginVC animated:YES];
                }else{
                    NSString *alert = ASLocalizedString(@"用户名或验证码错误");
                    if (error.code == 40002) {
                        alert = ASLocalizedString(@"验证码错误或失效");
                    }else if (error.code == BDLoginErrorLoginIMFailed) {
                        alert = @"极光IM登录失败";
                    }else if (error.code == BDLoginErrorGetFirendsListFailed) {
                        alert = @"获取好友列表失败";
                    }else if (error.code == BDLoginErrorGetGroupsListFailed) {
                        alert = @"获取好友列表失败";
                    }
                    
                    [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
                }
            }else{
                [MBManager hideAlert];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"getConvitasionFromDB" object:nil];
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            }
        }];
    }];
    
    //变更登录方式按钮
    [[self.changeLoginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
         BDLoginPasswordViewController *passVC = [[BDLoginPasswordViewController alloc] init];
        [self.navigationController pushViewController:passVC animated:YES];
    }];
}

- (void)jumpToPasswordLogin{
    BDLoginPasswordViewController *passVC = [[BDLoginPasswordViewController alloc] init];
    [self.navigationController pushViewController:passVC animated:YES];
}

- (UITextField *)userField{
    if (!_userField) {
        UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + 10, self.view.bounds.size.width, 45)];
        bkView.backgroundColor = [UIColor whiteColor];
        
        UIView *upLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        upLine.backgroundColor = kBDColorGray;
        [bkView addSubview:upLine];
        
        [self.view addSubview:bkView];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 40)];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        titleLabel.text = ASLocalizedString(@"手机号码");
        titleLabel.centerY = bkView.height / 2.0;
        [bkView addSubview:titleLabel];
        
        self.getButton.right = self.view.width - 10;
        self.getButton.centerY = bkView.height / 2.0;
        [bkView addSubview:_getButton];
        
        self.userField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, self.getButton.left - 100, 45)];
        _userField.font = [UIFont systemFontOfSize:14];
        _userField.tintColor = [UIColor lightGrayColor];
        _userField.borderStyle = UITextBorderStyleNone;
        [bkView addSubview:_userField];
        
    }
    return _userField;
}

- (UIButton *)getButton{
    if (!_getButton) {
        self.getButton = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = ASLocalizedString(@"获取验证码");
        [_getButton setTitle:title forState:UIControlStateNormal];
        _getButton.backgroundColor = kNOValidColor;
        _getButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _getButton.width = 90;
        _getButton.height = 35;
        _getButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        _getButton.layer.masksToBounds = YES;
        _getButton.layer.cornerRadius = 4;
    }
    return _getButton;
}

- (UITextField *)passField{
    if (!_passField) {
        UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + 10 + 45, self.view.bounds.size.width, 45)];
        bkView.backgroundColor = [UIColor whiteColor];
        bkView.layer.borderWidth = 0.5;
        bkView.layer.borderColor = kBDColorGray.CGColor;
        [self.view addSubview:bkView];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 40)];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        titleLabel.text = ASLocalizedString(@"验证码");
        titleLabel.centerY = bkView.height / 2.0;
        [bkView addSubview:titleLabel];
        
        self.passField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, self.view.bounds.size.width - 40, 45)];
        _passField.font = [UIFont systemFontOfSize:14];
        _passField.tintColor = [UIColor lightGrayColor];
        _passField.borderStyle = UITextBorderStyleNone;
        _passField.keyboardType = UIKeyboardTypeNumberPad;
        [bkView addSubview:_passField];
    }
    return _passField;
}

- (YYLabel *)xieyiLabel{
    if (!_xieyiLabel) {
        self.xieyiLabel = [[YYLabel alloc] init];
        _xieyiLabel.frame = CGRectMake(35, kBDTopHeight + 10 + 90 + 10, kBDScreenWidth - 20, 200);
        _xieyiLabel.textAlignment = NSTextAlignmentCenter;
        _xieyiLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
        _xieyiLabel.numberOfLines = 0;
        _xieyiLabel.textAlignment = NSTextAlignmentLeft;
        _xieyiLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        _xieyiLabel.backgroundColor = [UIColor clearColor];
        
        NSString *text = ASLocalizedString(@"已阅读并同意《用户服务协议》");
        NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString: text];
        //设置整段文本size
        one.font = [UIFont systemFontOfSize:14];
        one.lineSpacing = 2;
        // 获得range， 只设置标记文字的size、下划线
        NSRange range = [text rangeOfString:ASLocalizedString(@"《用户服务协议》")];
        //标记文字点击事件
        [one setTextHighlightRange:range color:KBDColorBlue backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            BDTishiViewController *tishiVC = [[BDTishiViewController alloc] init];
            tishiVC.xieyiType = BDXieyiTypeUser;
            [self.navigationController pushViewController:tishiVC animated:YES];
        }];
        _xieyiLabel.attributedText = one;
        [self.view addSubview:_xieyiLabel];
        YYTextLayout *layout = [YYTextLayout layoutWithContainer:[YYTextContainer containerWithSize:CGSizeMake(kBDScreenWidth - 20, MAXFLOAT)] text:one];
        _xieyiLabel.height = layout.textBoundingSize.height;
        
        self.agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _agreeButton.size = CGSizeMake(20, 20);
        _agreeButton.right = _xieyiLabel.left - 5;
        _agreeButton.centerY = _xieyiLabel.centerY;
        [_agreeButton setBackgroundImage:[UIImage imageNamed:@"xieyi_disagree"] forState:UIControlStateNormal];
        [_agreeButton setBackgroundImage:[UIImage imageNamed:@"xieyi_agree"] forState:UIControlStateSelected];
        [self.view addSubview:_agreeButton];
        
        [_agreeButton setEnlargeEdgeWithTop:5 right:30 bottom:5 left:10];
        
        [[_agreeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            _agreeButton.selected = !_agreeButton.selected;
        }];
    }
    return _xieyiLabel;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.frame = CGRectMake(10, self.xieyiLabel.bottom + 20, self.view.bounds.size.width - 20, 45);
        [_loginButton setTitle:ASLocalizedString(@"登录")forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginButton.backgroundColor = kLoginButtonColor;
        _loginButton.titleLabel.font = [UIFont systemFontOfSize:17];
        _loginButton.layer.masksToBounds = YES;
        _loginButton.layer.cornerRadius = 4;
        [self.view addSubview:_loginButton];
    }
    return _loginButton;
}

- (UIButton *)changeLoginButton{
    if (!_changeLoginButton) {
        self.changeLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = ASLocalizedString(@"密码登录 >>");
        [_changeLoginButton setTitle:title forState:UIControlStateNormal];
        [_changeLoginButton setTitleColor:KBDColorBlue forState:UIControlStateNormal];
        _changeLoginButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _changeLoginButton.size = CGSizeMake([title widthWithFont:_changeLoginButton.titleLabel.font], _changeLoginButton.titleLabel.font.pointSize);
        _changeLoginButton.top = self.loginButton.bottom + 20;
        _changeLoginButton.left = 10;
        [self.view addSubview:_changeLoginButton];
    }
    return _changeLoginButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
